package org.piwicode.bywordofmouth.net;

import com.google.common.base.Preconditions;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

/**
 *
 * @author pierre
 */
public class Server {

    private final Thread serverThread;
    private final ExecutorService executor;

    private Server(final Thread serverThread, final ExecutorService executor) {
        this.serverThread = Preconditions.checkNotNull(serverThread);
        this.executor = Preconditions.checkNotNull(executor);
    }

    public static Server start(final Object implem,final int port) {
        final ExecutorService executor = new CancellableExecutor(0, Integer.MAX_VALUE, 
                60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>());
        final Service service = new Service(implem);
        final ServerAcceptThread thread = new ServerAcceptThread(port, service, executor);
        thread.start();
        return new Server(thread, executor);
    }

    
    public void shutdown() throws InterruptedException {
        serverThread.interrupt();
        executor.shutdownNow();
        serverThread.join();//Should timeout and loop        
    }
}
